package com.mune.gulimall.ware.service.impl;

import com.mune.common.constant.WareConstant;
import com.mune.gulimall.ware.entity.PurchaseDetailEntity;
import com.mune.gulimall.ware.service.PurchaseDetailService;
import com.mune.gulimall.ware.service.WareSkuService;
import com.mune.gulimall.ware.vo.MergeVo;
import com.mune.gulimall.ware.vo.PurchaseDoneVo;
import com.mune.gulimall.ware.vo.PurchaseItemDoneVo;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mune.common.utils.PageUtils;
import com.mune.common.utils.Query;

import com.mune.gulimall.ware.dao.PurchaseDao;
import com.mune.gulimall.ware.entity.PurchaseEntity;
import com.mune.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
  @Autowired
  PurchaseDetailService detailService;
  @Autowired
  WareSkuService wareSkuService;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<PurchaseEntity> page = this.page(
            new Query<PurchaseEntity>().getPage(params),
            new QueryWrapper<PurchaseEntity>()
    );
    return new PageUtils(page);
  }

  @Override
  public PageUtils queryPageUnReceive(Map<String, Object> params) {
    IPage<PurchaseEntity> page = this.page(
            new Query<PurchaseEntity>().getPage(params),
            new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
    );

    return new PageUtils(page);


  }

  @Transactional
  @Override
  public void mergePurchase(MergeVo mergeVo) {
    Long purchaseId = mergeVo.getPurchaseId();
    PurchaseEntity purchaseEntity = this.baseMapper.selectById(purchaseId);
    if (purchaseEntity == null) {
      purchaseEntity = new PurchaseEntity();
      purchaseEntity.setCreateTime(new Date());
      purchaseEntity.setUpdateTime(new Date());
      purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
      this.save(purchaseEntity);
      purchaseId = purchaseEntity.getId();
    }
    if (purchaseEntity.getStatus() != WareConstant.PurchaseStatusEnum.CREATED.getCode() && purchaseEntity.getStatus() != WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
      return;
    List<Long> items = mergeVo.getItems();
    Long finalPurchaseId = purchaseId;
    List<PurchaseDetailEntity> collect = items.stream().map(i -> {
      PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
      detailEntity.setId(i);
      detailEntity.setPurchaseId(finalPurchaseId);
      detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
      return detailEntity;
    }).collect(Collectors.toList());
    detailService.updateBatchById(collect);
    PurchaseEntity entity = new PurchaseEntity();
    entity.setId(purchaseId);
    entity.setUpdateTime(new Date());
    this.updateById(entity);
  }

  @Override
  public void received(List<Long> ids) {
    // 确认当前采购单是新建或已分配状态
    List<PurchaseEntity> collect = ids.stream().map(id -> {
      PurchaseEntity byId = this.getById(id);
      return byId;
    }).filter(entity ->
            entity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || entity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()
    ).map(item -> {
      item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
      item.setUpdateTime(new Date());
      return item;
    }).collect(Collectors.toList());
    // 改变采购单的状态
    this.updateBatchById(collect);
    // 采购项的状态
    collect.forEach(item -> {
      List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());
      List<PurchaseDetailEntity> detailEntity = entities.stream().map(entity -> {
        PurchaseDetailEntity purchaseEntity = new PurchaseDetailEntity();
        purchaseEntity.setId(entity.getId());
        purchaseEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
        return purchaseEntity;
      }).collect(Collectors.toList());
      detailService.updateBatchById(detailEntity);
    });
  }

  @Transactional
  @Override
  public void done(PurchaseDoneVo doneVo) {
    // 改变采购单的状态
    Long id = doneVo.getId();

    // 改变采购项的状态
    Boolean flag = false;
    List<PurchaseDetailEntity> updates = new ArrayList<>();
    for (PurchaseItemDoneVo item : doneVo.getItems()) {
      PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
      if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
        flag = true;
        detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
      } else {
        detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
        PurchaseDetailEntity entity = detailService.getById(item.getItemId());
        wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
      }
      detailEntity.setId(item.getItemId());
      updates.add(detailEntity);
    }
    detailService.updateBatchById(updates);
    PurchaseEntity entity = new PurchaseEntity();
    entity.setId(id);
    entity.setStatus(flag ? WareConstant.PurchaseStatusEnum.HASERROR.getCode() : WareConstant.PurchaseStatusEnum.FINISH.getCode());
    entity.setUpdateTime(new Date());
    this.updateById(entity);

    // 将成功采购的进行入库
  }
}